<template>
  <div>
    <form class="card comment-form" @submit.prevent="onSubmit">
      <div class="card-block">
        <textarea v-model="comment.body" class="form-control" placeholder="Write a comment..." rows="3"></textarea>
      </div>
      <div class="card-footer">
        <img
          src="http://i.imgur.com/Qr71crq.jpg"
          class="comment-author-img"
        />
        <button class="btn btn-sm btn-primary">
          Post Comment
        </button>
      </div>
    </form>
    
    <div
      class="card"
      v-for="comment in comments"
      :key="comment.id"
    >
      <div class="card-block">
        <p class="card-text">
          {{ comment.body }}
        </p>
      </div>
      <div class="card-footer">
        <nuxt-link :to="{
          name: 'profile',
          params: {
            username: comment.author.username
          }
        }" class="comment-author">
          <img :src="comment.author.image" class="comment-author-img" />
        </nuxt-link>
        &nbsp;
        <nuxt-link :to="{
          name: 'profile',
          params: {
            username: comment.author.username
          }
        }" class="comment-author">
          {{ comment.author.username }}
        </nuxt-link>
        <span class="date-posted">{{ comment.createdAt | date('MMM DD, YYYY')}}</span>
        <span class="mod-options" v-if="isCommentUser(comment)">
          <i class="ion-trash-a" @click="onDelete(comment.id)"></i>
        </span>
      </div>
    </div>
        
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getComments, addComment, deleteComment } from '@/api/article'
import MarkdownIt from 'markdown-it'

export default {
  name: 'ArticleComments',
  props: {
    article: {
      type: Object,
      required: true
    }
  },
  computed: {
    ...mapState(['user']),
    isCommentUser(comment) {
      if (!this.user) {
        return false
      }
      return function(comment){
        console.log(comment)
        return comment.author.username === this.user.username        
      }           
    }
  },
  data () {
    return {
      comment: {
        body: ''
      },
      comments: []
    }
  },
  mounted () {
    this.getCommentsList()
  },
  methods: {
    async onSubmit () {
      if (!this.user) {
        return
      }
      try {
        const { data } = await addComment(this.article.slug, {
          comment: this.comment
        })
        this.comment.body = ''
        this.getCommentsList()
      } catch (error) {
        // ignore 
      }
    },
    async getCommentsList() {
      const { data } = await getComments(this.article.slug)
      const { comments } = data

      this.comments = comments
    },
    async onDelete(id) {
      const { data } = await deleteComment(this.article.slug, id)
      this.getCommentsList()
    }
  }
}
</script>

<style>

</style>